var mapData = Array(); //地图数据
var saveJson; //json地图数据
// mapData中的每个数据对象的解释
// mapType表示图片类型，x表示x坐标，y表示y坐标,
// mapType值
// s1-1，单工单升堆垛机-水平-left；s1-2，单工单升堆垛机-水平-right;s2-3，单工单升堆垛机-垂直-up;s2-4，单工单升堆垛机-垂直-down
// c1-1，输送线-水平-left; c1-2，输送线-水平-right; c1-3，输送线-水平-up; c1-4，输送线-水平-down;
// c2-1，输送线-垂直-left; c2-2，输送线-垂直-right; c2-3，输送线-垂直-up; c2-4，输送线-垂直-down;
// b1-1，BCR-left; b1-2，BCR-right; b2-1，BCR-up; b2-1，BCR-down;
// room，仓库位; wall，墙体; water，水箱
var ddj = Array();
var ssj = Array();
var rrj = Array();
var mpj = Array();
var tsj = Array();
var cpj = Array();
var dpj = Array();
var tk = ["格子 1", "格子 2", "格子 3"];
//文字
var txt = {
  add: function (id, x, y, title, size) {
    if (size == null) size = 12;
    $("#txt" + id + "").remove();
    var map = $("#zd_map");
    var box =
      '<div id="txt' +
      id +
      '" style="position:absolute;font-size:' +
      size +
      'px;">' +
      title +
      "</div>";
    map.append(box);
    x = x * step;
    y = y * step;
    $("#txt" + id + "").css({ x: x + "px", y: y + "px" });
  },
  remove: function (id) {
    $("#txt" + id + "").remove();
  },
};

// 区域标注
var areatxt = {
  add: function (id, x, y, title, obj) {
    var step = 34;
    $("#areatxt" + id + "").remove();
    var size = obj.size.split(" ");
    var map = $("#zd_map");
    var hasBorder = obj.hasBorder ? "area-text-box" : "";
    var titleBox = `<span class="title" style="font-size:${obj.fontSize}px;font-weight:600;">${obj.title}</span>`;
    var box = `<div id="areatxt${id}" class="${hasBorder}" style="position:absolute;width:${size[0]}px;height:${size[1]}px;">${titleBox}</div>`;
    map.append(box);
    x = x * step;
    y = y * step;
    $(`#areatxt${id}`).css({ x: x + "px", y: y + "px" });
  },
  remove: function (id) {
    $("#areatxt" + id + "").remove();
  },
};

//仓库
var ck = {
  add: function (id, x, y, title) {
    var step = 34;
    //var x = pos[0];
    //var y = pos[1];
    $("#ck" + id + "").remove();
    var map = $("#zd_map");
    var box =
      '<div id="ck' +
      id +
      '" style="position:absolute;font-size:12px;background:url(../map/images/cangwei.png) no-repeat;width:34px; height:34px;"><span id="cktxt' +
      id +
      '">' +
      title +
      "</span></div>";
    map.append(box);
    x = x * step;
    y = y * step;
    $("#ck" + id + "").css({ x: x + "px", y: y + "px" });
    $("#cktxt" + id + "").css({ x: x + "px", y: y + "px" });
    //鼠标事件
    $("#ck" + id + "").on({
      mouseover: function (event) {
        createOrUpdateContent(id, tk);
      },
      mouseout: function () {
        layer.close(index);
        $("#ck" + id + "").css("cursor", "auto");
      },
    });
  },
  remove: function (id) {
    $("#ck" + id + "").remove();
  },
};
//处理数据
function changeTK(data) {
  var one = [];
  var two = [];
  var three = [];
  var four = [];
  var five = [];
  var six = [];
  var seven = [];
  var eight = [];
  var nine = [];
  var ten = [];
  var newList = [];
  data.forEach(function (item) {
    if (item.lay == 1) {
      one.push(item);
    } else if (item.lay == 2) {
      two.push(item);
    } else if (item.lay == 3) {
      three.push(item);
    } else if (item.lay == 4) {
      four.push(item);
    } else if (item.lay == 5) {
      five.push(item);
    } else if (item.lay == 6) {
      six.push(item);
    } else if (item.lay == 7) {
      seven.push(item);
    } else if (item.lay == 8) {
      eight.push(item);
    } else if (item.lay == 9) {
      nine.push(item);
    } else if (item.lay == 10) {
      ten.push(item);
    }
  });
  newList.push(one);
  newList.push(two);
  newList.push(three);
  newList.push(four);
  newList.push(five);
  newList.push(six);
  newList.push(seven);
  newList.push(eight);
  newList.push(nine);
  newList.push(ten);
  tk = newList;
}
 // 定义一个对象来存储特定格子的颜色配置 红色异常 绿色有货  蓝色入库   橙色出库
 var colorConfig = {
};
// 定义一个函数来创建内容，并允许更新
function createOrUpdateContent(id, contentArray) {
  if (id >= 1 && id <= 54) {
    // 修改逻辑以适应id在1-54之间的情况
    var content = '<div class="eight-by-nine-grid">';
    //console.log(contentArray);
    //处理contentArray
    if (id >= 1 && id <= 9) {
      updateColorConfig(contentArray[0]);
    }
    if (id >= 10 && id <= 18) {
      updateColorConfig(contentArray[1]);
    }
    if (id >= 19 && id <= 27) {
      updateColorConfig(contentArray[2]);
    }
    if (id >= 28 && id <= 36) {
      updateColorConfig(contentArray[3]);
    }
    if (id >= 37 && id <= 45) {
      updateColorConfig(contentArray[4]);
    }
    if (id >= 46 && id <= 54) {
      updateColorConfig(contentArray[5]);
    }
    for (var i = 8; i >= 1; i--) {
      content += '<div class="grid-row">';
      for (var j = 1; j < 10; j++) {
        var rowLabel = j === 1 ? '<div class="row-label">' + i +"层"+ "</div>" : "";
        var colLabel = i === 1 ? '<div class="col-label">' + j +"列"+ "</div>" : "";

        // 使用对象来获取背景颜色，如果没有定义则使用默认颜色
        var backgroundColor = colorConfig[i + "-" + j] || "#defaultColor";
        content +=
          '<div class="grid-item" style="background-color: ' +
          backgroundColor +
          ';">' +
          rowLabel +
          colLabel +
          "</div>";
      }
      content += "</div>";
    }
    content += "</div>";

    index = layer.tips(content, "#ck" + id + "", {
      tips: [1, "#fff"],
      time: 0,
      follow: true, // 自适应跟随鼠标
      maxWidth: 600, // 增加最大宽度以适应更宽的内容
      maxHeight: 400, // 增加最大高度以适应更高的内容
      success: function (layero) {
        // 确保悬浮窗不超出屏幕边界
        layero.css({
          left: Math.min(
            event.pageX + 10,
            $(window).width() - layero.outerWidth() - 10
          ),
          top: Math.min(
            event.pageY + 10,
            $(window).height() - layero.outerHeight() - 10
          ),
        });
      },
    });

    $("#ck" + id + "").css("cursor", "pointer");
    colorConfig = {
    };
  } else if (id >= 100) {
    // 修改逻辑以适应id在100-153之间的情况
    var content = '<div class="three-by-three-grid">';
    //处理contentArray
    if (id >= 100 && id <= 102) {
      updateColorConfig(contentArray[6]);
    }
    if (id >= 103 && id <= 105) {
      updateColorConfig(contentArray[7]);
    }
    if (id >= 106 && id <= 108) {
      updateColorConfig(contentArray[8]);
    }
    if (id >= 109 && id <= 111) {
      updateColorConfig(contentArray[9]);
    }
    for (var i = 3; i >= 1; i--) {
      content += '<div class="grid-row">';
      for (var j = 1; j < 4; j++) {
        var rowLabel =
          j ===1 ? '<div class="row-label">' + i +"层"+ "</div>" : "";
        var colLabel =
          i === 1 ? '<div class="col-label">' + j +"列"+ "</div>" : "";
        // 使用对象来获取背景颜色，如果没有定义则使用默认颜色
        var backgroundColor = colorConfig[i + "-" + j] || "#defaultColor";
        content +=
          '<div class="grid-item" style="background-color: ' +
          backgroundColor +
          ';">' +
          rowLabel +
          colLabel +
          "</div>";
      }
      content += "</div>";
    }
    content += "</div>";

    index = layer.tips(content, "#ck" + id + "", {
      tips: [1, "#fff"],
      time: 0,
      follow: true, // 自适应跟随鼠标
      maxWidth: 600, // 增加最大宽度以适应更宽的内容
      maxHeight: 400, // 增加最大高度以适应更高的内容
      success: function (layero) {
        // 确保悬浮窗不超出屏幕边界
        layero.css({
          left: Math.min(
            event.pageX + 10,
            $(window).width() - layero.outerWidth() - 10
          ),
          top: Math.min(
            event.pageY + 10,
            $(window).height() - layero.outerHeight() - 10
          ),
        });
      },
    });

    $("#ck" + id + "").css("cursor", "pointer");
    colorConfig = {
    };
  }
}

function updateColorConfig(contentArray) {
  console.log(contentArray);
  contentArray.forEach(function (item) {
    switch (item.status) {
      case "in":
        colorConfig[item.row + "-" + item.col] = "#1890ff";
        break;
      case "out":
        colorConfig[item.row + "-" + item.col] = "#1890ff";
        break;
      case "stock":
        colorConfig[item.row + "-" + item.col] = "#52c41a";
        break;
      case "error":
        colorConfig[item.row + "-" + item.col] = "#ff4d4f";
        break;
      case "empty":
        colorConfig[item.row + "-" + item.col] = "white";
        break;
        default:
        break;
    }
  });
  console.log(colorConfig);
}

function findInContentArray(contentArray, i, j) {
  var targetRow = 1; // 要查找的row值
  var targetLay = i; // 要查找的lay值
  var targetCol = j; // 要查找的col值

  for (var index = 0; index < contentArray.length; index++) {
    var item = contentArray[index];
    if (
      item.row === targetRow &&
      item.lay === targetLay &&
      item.col === targetCol
    ) {
      return item; // 找到匹配的数据，返回该项
    }
  }

  return null; // 如果没有找到匹配的数据，返回null
}

/**
 *
 * 查找数组，返回匹配到的第一个index
 *
 * @param array 被查找的数组
 * @param feature 查找特征 或者为一个具体值，用于匹配数组遍历的值，或者为一个对象，表明所有希望被匹配的key-value
 * @param or boolean 希望命中feature全部特征或者只需命中一个特征，默认true
 *
 * @return 数组下标  查找不到返回-1
 */
function findArray(array, feature, all = true) {
  for (let index in array) {
    let cur = array[index];
    if (feature instanceof Object) {
      let allRight = true;
      for (let key in feature) {
        let value = feature[key];
        if (cur[key] == value && !all) return index;
        if (all && cur[key] != value) {
          allRight = false;
          break;
        }
      }
      if (allRight) return index;
    } else {
      if (cur == feature) {
        return index;
      }
    }
  }
  return -1;
}

//数组去null
function ClearNullArr(arr) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (!arr[i] || arr[i] == "" || arr[i] === undefined) {
      arr.splice(i, 1);
      len--;
      i--;
    }
  }
  return arr;
}

//绘制地图网格
function newMap() {
  //初始化对象
  var demo = new blockDrag({ block: [240, 130] });
  //设置背景栅格，可根据需要添加
  var blockNum = Number(demo.col) * Number(demo.row);

  for (var i = 0; i < blockNum; i++) {
    $(
      "<div class='block' style='width:" +
        demo.set.blockW +
        "px;height:" +
        demo.set.blockH +
        "px'></div>"
    ).appendTo($("#zd_map"));
  }
}

///////////////////////////////////////////////////////////////////////////////
//
//	加载***********************************************************************
//
///////////////////////////////////////////////////////////////////////////////
//把数据解析到地图舞台上
function mapDataToScene(jsonStr) {
  var s1 = Array();
  var c1 = Array();
  var r1 = Array();
  var co1 = Array();
  var ts1 = Array();
  var cp1 = Array();
  var first;
  var str_code;
  var count_num;
  mapData = jsonStr;
  for (var i = 0; i < mapData.length; i++) {
    var obj = mapData[i];
    var itemType;
    if (!!obj.mapType) {
      itemType = obj.mapType.split("-");
    } else {
      itemType = "";
    }
    str_code = obj.code;
    switch (itemType[0]) {
      case "s1":
        s1[str_code] = Stacker.createNew();
        s1[str_code].setPos(
          i,
          obj.x,
          obj.y,
          obj.count_num,
          1,
          obj.direction,
          obj.movestep
        );
        s1[str_code].add(
          0,
          0,
          0,
          0,
          0,
          obj.code,
          obj.alarmMessage,
          [obj.x, obj.y],
          obj
        );
        break;
      case "s2":
        s1[str_code] = Stacker.createNew();
        s1[str_code].setPos(
          i,
          obj.x,
          obj.y,
          obj.count_num,
          2,
          obj.direction,
          obj.movestep
        );
        s1[str_code].add(
          0,
          0,
          0,
          0,
          0,
          obj.code,
          obj.alarmMessage,
          [obj.x, obj.y],
          obj
        );
        break;
      case "r1":
        r1[str_code] = Rgv.createNew();
        r1[str_code].setPos(
          i,
          obj.x,
          obj.y,
          obj.count_num,
          1,
          obj.direction,
          obj.movestep
        );
        r1[str_code].add(
          0,
          0,
          0,
          0,
          0,
          obj.code,
          obj.alarmMessage,
          [obj.x, obj.y],
          obj
        );
        break;
      case "r2":
        r1[str_code] = Rgv.createNew();
        r1[str_code].setPos(
          i,
          obj.x,
          obj.y,
          obj.count_num,
          2,
          obj.direction,
          obj.movestep
        );
        r1[str_code].add(
          0,
          0,
          0,
          0,
          0,
          obj.code,
          obj.alarmMessage,
          [obj.x, obj.y],
          obj
        );
        break;
      case "c1":
        c1[str_code] = Convey.createNew();
        c1[str_code].setPos(i, obj.x, obj.y, 1, 1, intToDire(itemType[1]));
        c1[str_code].add(
          0,
          0,
          0,
          0,
          obj.title,
          obj.code,
          itemType[1],
          0,
          0,
          obj
        );
        break;
      case "c2":
        c1[str_code] = Convey.createNew();
        c1[str_code].setPos(i, obj.x, obj.y, 1, 2, intToDire(itemType[1]));
        c1[str_code].add(
          0,
          0,
          0,
          0,
          obj.title,
          obj.code,
          itemType[1],
          0,
          0,
          obj
        );
        break;
      case "b1":
        bcr.add(i, obj.x, obj.y, obj.code, obj);
        break;
      case "room":
        ck.add(i, obj.x, obj.y, obj.code, obj);
        break;
      case "areatext":
        areatxt.add(i, obj.x, obj.y, obj.code, obj);
        break;
      case "hoist":
        ts1[str_code] = Hoist.createNew();
        ts1[str_code].setPos(i, obj.x, obj.y);
        ts1[str_code].add(0, 0, 0, 0, obj.code, obj);
        break;
      case "conveys":
        bw.add(i, obj.x, obj.y, intToDire(itemType[1]), obj.code, obj);
        break;
      case "WALL":
        qiang.add(i, obj.x, obj.y);
        break;
      case "tisheng":
        tisheng.add(i, obj.x, obj.y);
        break;
      case "double":
        double.add(i, obj.x, obj.y);
        break;
      case "doubles":
        doubles.add(i, obj.x, obj.y);
        break;
      case "coders":
        coders.add(i, obj.x, obj.y);
        break;
      case "discharge":
        cp1[str_code] = Discharge.createNew();
        cp1[str_code].setPos(i, obj.x, obj.y);
        cp1[str_code].add(0, 0, 0, 0, obj.code, obj.code), obj;
        break;

      case "wrapping":
        cm.add(i, obj.x, obj.y, obj.code, obj.code), obj;
        break;
      case "coder":
        co1[str_code] = Coder.createNew();
        co1[str_code].setPos(i, obj.x, obj.y);
        co1[str_code].add(0, 0, 0, 0, obj.code, obj.code, obj);
        break;
      case "water":
        sx.add(i, obj.x, obj.y);
        break;
      case "guidao":
        guidao.add(i, obj.x, obj.y, itemType[1]);
        break;
    }
  }
  ddj = s1;
  ssj = c1;
  rrj = r1;
  dpj = co1;
  tsj = ts1;
  cpj = cp1;
}

function intToDire(value) {
  var res;
  switch (parseInt(value)) {
    case 1:
      res = "left";
      break;
    case 2:
      res = "right";
      break;
    case 3:
      res = "up";
      break;
    case 4:
      res = "down";
      break;
    case 5:
      res = "double";
      break;
    case 6:
      res = "left";
      break;
    case 7:
      res = "right";
      break;
    case 8:
      res = "up";
      break;
    case 9:
      res = "down";
      break;
    case 10:
      res = "doubles";
      break;
  }
  return res;
}

function mapDataToUp(jsonStr) {
  var mapData = jQuery.parseJSON(jsonStr);
  for (var i = 0; i < mapData.length; i < i++) {
    mapData[i].y = mapData[i].y + 20;
  }
  var s1 = Array();
  var c1 = Array();
  var r1 = Array();
  var co1 = Array();
  var ts1 = Array();
  var cp1 = Array();
  for (var i = 0; i < mapData.length; i++) {
    var obj = mapData[i];
    var itemType = obj.mapType.split("-");

    // console.log(itemType)
    switch (itemType[0]) {
      case "s1":
        s1[i] = Stacker.createNew();
        s1[i].setPos(i, obj.x, obj.y, 1, 1, intToDire(itemType[1]));
        s1[i].mapAdd();
        break;
      case "s2":
        s1[i] = Stacker.createNew();
        s1[i].setPos(i, obj.x, obj.y, 1, 2, intToDire(itemType[1]));
        s1[i].mapAdd();
        break;
      case "c1":
        c1[i] = Convey.createNew();
        c1[i].setPos(i, obj.x, obj.y, 1, 1, intToDire(itemType[1]));
        c1[i].mapAdd();
        break;
      case "c2":
        c1[i] = Convey.createNew();
        c1[i].setPos(i, obj.x, obj.y, 1, 2, intToDire(itemType[1]));
        c1[i].mapAdd();
        break;
      case "b1":
        bcr.mapAdd(i, obj.x, obj.y, intToDire(itemType[1]));
        break;
      case "room":
        ck.mapAdd(i, obj.x, obj.y);
        break;
      case "conveys":
        bw.mapAdd(i, obj.x, obj.y, intToDire(itemType[1]));
        break;
      case "hoist":
        ts1[i] = Hoist.createNew();
        ts1[i].setPos(i, obj.x, obj.y);
        ts1[i].mapAdd();
        break;
      case "discharge":
        cp1[i] = Discharge.createNew();
        cp1[i].setPos(i, obj.x, obj.y);
        cp1[i].mapAdd();
        break;
      case "wall":
        qiang.mapAdd(i, obj.x, obj.y);
        break;

      case "wrapping":
        cm.mapAdd(i, obj.x, obj.y);
        break;
      case "coder":
        co1[i] = Coder.createNew();
        co1[i].setPos(i, obj.x, obj.y);
        co1[i].mapAdd();
        break;
      case "water":
        sx.mapAdd(i, obj.x, obj.y);
        break;
      case "guidao":
        guidao.mapAdd(i, obj.x, obj.y, itemType[1]);
        break;
      case "rgv":
        r1[i] = Rgv.createNew();
        r1[i].setPos(i, obj.x, obj.y, obj.idnumber, itemType[1]);
        r1[i].mapAdd();
        break;
    }
  }

  saveJson = JSON.stringify(ClearNullArr(mapData));
  //console.log(saveJson);
}

function mapDataToleft(jsonStr) {
  var mapData = jQuery.parseJSON(jsonStr);
  //console.log(mapData);
  for (var i = 0; i < mapData.length; i < i++) {
    mapData[i].x = mapData[i].x - 2;
  }
  var s1 = Array();
  var c1 = Array();
  var r1 = Array();
  var co1 = Array();
  var ts1 = Array();
  var cp1 = Array();
  for (var i = 0; i < mapData.length; i++) {
    var obj = mapData[i];
    var itemType = obj.mapType.split("-");

    // console.log(itemType)
    switch (itemType[0]) {
      case "s1":
        s1[i] = Stacker.createNew();
        s1[i].setPos(i, obj.x, obj.y, 1, 1, intToDire(itemType[1]));
        s1[i].mapAdd();
        break;
      case "s2":
        s1[i] = Stacker.createNew();
        s1[i].setPos(i, obj.x, obj.y, 1, 2, intToDire(itemType[1]));
        s1[i].mapAdd();
        break;
      case "c1":
        c1[i] = Convey.createNew();
        c1[i].setPos(i, obj.x, obj.y, 1, 1, intToDire(itemType[1]));
        c1[i].mapAdd();
        break;
      case "c2":
        c1[i] = Convey.createNew();
        c1[i].setPos(i, obj.x, obj.y, 1, 2, intToDire(itemType[1]));
        c1[i].mapAdd();
        break;
      case "b1":
        bcr.mapAdd(i, obj.x, obj.y, intToDire(itemType[1]));
        break;
      case "room":
        ck.mapAdd(i, obj.x, obj.y);
        break;
      case "hoist":
        ts1[i] = Hoist.createNew();
        ts1[i].setPos(i, obj.x, obj.y);
        ts1[i].mapAdd();
        break;

      case "conveys":
        // images/conveys_' + angle + '.png
        bw.mapAdd(i, obj.x, obj.y, intToDire(itemType[1]));
        break;
      case "wall":
        qiang.mapAdd(i, obj.x, obj.y);
        break;
      case "discharge":
        cp1[i] = Discharge.createNew();
        cp1[i].setPos(i, obj.x, obj.y);
        cp1[i].mapAdd();
        break;
      case "wrapping":
        cm.mapAdd(i, obj.x, obj.y);
        break;
      case "coder":
        co1[i] = Coder.createNew();
        co1[i].setPos(i, obj.x, obj.y);
        co1[i].mapAdd();
        break;
      case "water":
        sx.mapAdd(i, obj.x, obj.y);
        break;
      case "guidao":
        // images/rgv_track_1.png
        guidao.mapAdd(i, obj.x, obj.y, itemType[1]);
        break;
      case "rgv":
        r1[i] = Rgv.createNew();
        r1[i].setPos(i, obj.x, obj.y, obj.idnumber, itemType[1]);
        r1[i].mapAdd();
        break;
    }
  }
  saveJson = JSON.stringify(ClearNullArr(mapData));
  //console.log(saveJson);
}
